package day21.fefei.homework;


//import javafx.print.Collation;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

import java.util.Collection;
import java.util.Scanner;

public class ServerTCP {
    public static void main(String[] args) throws Exception {
        System.out.println("服务端已启动，等待客户端连接---");
        ServerSocket server = new ServerSocket(8088);
        Socket socket = server.accept();
        System.out.println("接收到一个客户端，建立了通信");
        Send send = new Send("服务端发送", socket);
        Accept accept = new Accept("服务端接收", socket);
        new Thread(()->{});
        send.start();
        accept.start();

    }
}

class CilentTCP{
    public static void main(String[] args) throws Exception {

        System.out.println("客户端已经启动，正在连接服务端---");
        InetAddress localHost = InetAddress.getLocalHost();
        Socket socket = new Socket(localHost, 8088);
        System.out.println("服务端已经连接成功，建立了连接");
        Send send = new Send("客户端发送", socket);
        Accept accept = new Accept("客户端接收", socket);
        send.start();
        accept.start();
    }
}
class Send extends Thread {
    private Socket socket;

    public Send(String name, Socket socket) {
        super(name);
        this.socket = socket;
    }

    @Override
    public void run() {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            String inputContent = scanner.next();
            // 转换字节数组
            byte[] bytes = inputContent.getBytes();
            OutputStream os = null;
            try {
                os = socket.getOutputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                os.write(bytes);// 发送一次
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 结束标志
            if (inputContent.contains("over")) {
                break;
            }
        }
    }
}

class Accept extends Thread {

    private Socket socket;

    public Accept(String name, Socket socket) {
        super(name);
        this.socket = socket;
    }

    @Override
    public void run() {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            // 接收来自于服务器端的信息
            InputStream is = null;
            try {
                is = socket.getInputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
            byte[] data = new byte[1024];
            int read = 0;
            try {
                read = is.read(data);
            } catch (IOException e) {
                e.printStackTrace();
            }
            String receive = new String(data, 0, read);
            System.out.println("从服务器端接收到的信息" + new String(data, 0, read));
            if (receive.contains("over")) {
                break;
            }
        }
    }
}